package com.imooc.web.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition;
import com.imooc.service.UserService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 认证用户的全部信息
	 * {
	 * "authorities":[{"authority":"admin"}],
	 * "details":{"remoteAddress":"0:0:0:0:0:0:0:1","sessionId":"43AF42F0B67B3B7960CE61A0A84E2812"},
	 * "authenticated":true,
	 * "principal":{
	 * 		"password":null,
	 * 		"username":"qwert",
	 * 		"authorities":[{"authority":"admin"}],
	 * 		"accountNonExpired":true,		
	 * 		"accountNonLocked":true,
	 * 		"credentialsNonExpired":true,
	 * 		"enabled":true},
	 * "credentials":null,
	 * "name":"qwert"
	 * }
	 * @return
	 */
	@GetMapping("me")
	public Object getMe(Authentication authentication) {
		//return SecurityContextHolder.getContext().getAuthentication();
		return authentication;
	}
	
	/**
	 * 认证用户的基本信息（即principal）
	 * @return
	 */
	@GetMapping("loginuser")
	public Object getLoginUserDetails(@AuthenticationPrincipal UserDetails user) {
		return user;
	}
	
	@DeleteMapping("{id:\\d+}")
	@ApiOperation(value = "deleteUserById() 删除用户")
	public String deleteUserById(@ApiParam(value="用户ID") @PathVariable("id") String id) {
		System.out.println("删除的用户的ID："+id);
		return "1";
	}
	
	@PutMapping
	@ApiOperation(value = "updateUser() 更新用户信息")
	public User updateUser(@ApiParam(value="用户") @Valid @RequestBody User user, BindingResult errors) {
		if(errors.hasErrors()) {
			errors.getAllErrors().stream().forEach(error -> System.out.println(error.getObjectName()+":"+error.getDefaultMessage()));
		}
		user.setId(5);
		return user;
	}
	
	@PostMapping
	@ApiOperation(value = "createUser() 创建用户")
	public User createUser(@ApiParam(value="用户") @RequestBody User user) {
		System.out.println(user.toString());
		user.setId(5);
		return user;
	}

	/**
	 * 
	 * @param condition 条件查询参数
	 * @param pageable 分页参数（SpringData提供）
	 * @return
	 */
	@GetMapping(value = "")
	@ApiOperation(value = "getUsers() 获取用户列表")
	@JsonView(User.UserListView.class)
	public List<User> getUsers(
			  UserQueryCondition condition
			, @PageableDefault(page=3, size=20, sort="name,asc") Pageable pageable) {
		return userService.getUsers(condition, pageable);
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 * 使用正則对URL进行限制，id只能是数字
	 */
	@GetMapping(value = "{id:\\d+}")
	@ApiOperation(value = "getInfo() 获取用户详细信息")
	@JsonView(User.UserInfoView.class)
	public User getInfo(@ApiParam(value="用户ID") @PathVariable("id") String id) {
//		throw new UserNotExistException("用户（ID:"+id+"）不存在");
		return userService.getInfo(id);
	}
	
}
